package com.evolution.common.security.context;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaStorage;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.evolution.common.core.constant.GlobalConstant;
import com.evolution.common.core.enums.UserType;
import com.evolution.common.security.entity.User;

import java.util.Set;
import java.util.function.Supplier;

/**
 * Class: LoginContext
 * <p>
 * desc:
 * </p>
 * create date: 2024-03-07 17:58:45
 *
 * @author cao.yong
 */
public class LoginContext {

    public static final String USER_KEY = "user";
    public static final String TENANT_ID_KEY = "tenantId";
    public static final String USER_ID_KEY = "userId";
    public static final String DEPT_ID_KEY = "deptId";
    public static final String CLIENT_ID_KEY = "clientId";
    public static final String TENANT_ADMIN_KEY = "isTenantAdmin";

    /**
     * 登录系统 基于 设备类型
     * 针对相同用户体系不同设备
     *
     * @param user  登录用户信息
     * @param model 配置参数
     */
    public static void login(User user, SaLoginModel model) {
        SaStorage storage = SaHolder.getStorage();
        storage.set(USER_KEY, user);
        storage.set(TENANT_ID_KEY, user.getTenantId());
        storage.set(USER_ID_KEY, user.getUserId());
        storage.set(DEPT_ID_KEY, user.getDeptId());
        model = ObjectUtil.defaultIfNull(model, new SaLoginModel());
        StpUtil.login(user.getLoginId(),
                model.setExtra(TENANT_ID_KEY, user.getTenantId())
                        .setExtra(USER_ID_KEY, user.getUserId())
                        .setExtra(DEPT_ID_KEY, user.getDeptId()));
        SaSession tokenSession = StpUtil.getTokenSession();
        tokenSession.updateTimeout(model.getTimeout());
        tokenSession.set(USER_KEY, user);
    }

    /**
     * 获取用户(多级缓存)
     */
    public static User getUser() {
        return (User) getStorageIfAbsentSet(USER_KEY, () -> {
            SaSession session = StpUtil.getTokenSession();
            if (ObjectUtil.isNull(session)) {
                return null;
            }
            return session.get(USER_KEY);
        });
    }

    /**
     * 获取用户基于token
     */
    public static User getUser(String token) {
        SaSession session = StpUtil.getTokenSessionByToken(token);
        if (ObjectUtil.isNull(session)) {
            return null;
        }
        return (User) session.get(USER_KEY);
    }

    /**
     * 获取用户id
     */
    public static Long getUserId() {
        return Convert.toLong(getExtra(USER_ID_KEY));
    }

    /**
     * 获取租户ID
     */
    public static Long getTenantId() {
        return Convert.toLong(getExtra(TENANT_ID_KEY));
    }

    /**
     * 获取部门ID
     */
    public static Long getDeptId() {
        return Convert.toLong(getExtra(DEPT_ID_KEY));
    }

    private static Object getExtra(String key) {
        return getStorageIfAbsentSet(key, () -> {
            return StpUtil.getExtra(key);
        });
    }

    /**
     * 获取用户账户
     */
    public static String getUsername() {
        return getUser().getUsername();
    }

    /**
     * 获取用户类型
     */
    public static UserType getUserType() {
        String loginType = StpUtil.getLoginIdAsString();
        return UserType.of(loginType);
    }

    /**
     * 是否为超级管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isSuperAdmin(Long userId) {
        return GlobalConstant.SUPER_ADMIN_ID.equals(userId);
    }

    public static boolean isSuperAdmin() {
        return isSuperAdmin(getUserId());
    }

    /**
     * 是否为超级管理员
     *
     * @param rolePermission 角色权限标识组
     * @return 结果
     */
    public static boolean isTenantAdmin(Set<String> rolePermission) {
        return rolePermission.contains(GlobalConstant.TENANT_ADMIN_ROLE_KEY);
    }

    public static boolean isTenantAdmin() {
        Object value = getStorageIfAbsentSet(TENANT_ADMIN_KEY, () -> isTenantAdmin(getUser().getRolePermission()));
        return Convert.toBool(value);
    }

    public static boolean isLogin() {
        return getUser() != null;
    }

    public static Object getStorageIfAbsentSet(String key, Supplier<Object> handle) {
        try {
            Object obj = SaHolder.getStorage().get(key);
            if (ObjectUtil.isNull(obj)) {
                obj = handle.get();
                SaHolder.getStorage().set(key, obj);
            }
            return obj;
        } catch (Exception e) {
            return null;
        }
    }
}
